<template>
  <div>
    <a-modal
      v-model="visible"
      title="添加用户"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <!-- 表单部分 -->
      <a-form-model
        ref="ruleForm"
        :model="userForm"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="userForm.username" />
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input v-model="userForm.password" />
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="userForm.email" />
        </a-form-model-item>
        <a-form-model-item label="手机" prop="mobile">
          <a-input v-model="userForm.mobile" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { checkEmail, chenckMobile } from "../../../utils/check";
export default {
  data() {
    return {
      visible: false,
      userForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "用户名长度在3~10之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "用户名长度在6~15之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: chenckMobile, trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    //确定按钮
    handleOk(e) {
      this.visible = false;
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        try {
          await this.$store.dispatch("getAdd", this.userForm);
          this.$message.success("添加成功！");
          this.$emit('refresh')
        } catch (error) {
          alert(error.message);
          this.$message.warning("添加失败！");
        }
      });
    },
    // 取消
    handleCancel(e) {
      this.visible = false;
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>